package net.cathackers.devel.scmp.chat.impl.xmpp.messageComponent;

import java.util.List;

import org.apache.log4j.Logger;

import net.cathackers.devel.scmp.auth.interfaces.UserID;
import net.cathackers.devel.scmp.chat.backend.mysql.MySQLOfflineStoreBackend;
import net.cathackers.devel.scmp.exceptions.BackendException;
import net.cathackers.devel.scmp.factories.SCMPFactory;
import net.cathackers.devel.scmp.xmpp.Packet;

public class OfflineMessageStoreImpl implements OfflineMessageStore {
    private Logger logger_;
    private MySQLOfflineStoreBackend backend_;

    public OfflineMessageStoreImpl(MySQLOfflineStoreBackend backend) {
	logger_ = SCMPFactory.getLogger(this);
	backend_ = backend;
    }

    public List<OfflineMessage> getOfflineMessage(UserID userID) {
	List<OfflineMessage> ret = null;
	if (userID != null) {
	    this.openConnection();
	    ret = backend_.getMessages(userID);
	}
	return ret;
    }

    public void storeOfflineMessage(Packet packet) {
	if (packet != null) {
	    // TODO we must check if the userID(to) is registered userID
	    if (packet.getTo() != null) {
		this.openConnection();
		backend_.addOfflineMessage(packet);
	    }
	}
    }

   /* private void closeConnection() {
	try {
	    if (backend_.isConnected()) {
		backend_.disconnect();
	    }
	} catch (CATException ex) {
	    logger_
		    .error("Error while communicating with backend, disconnect(): "
			    + ex.getMessage());

	}

    }*/

    private void openConnection() {
	if (!backend_.isConnected()) {
	    try {
		backend_.connect();
	    } catch (BackendException e) {
		logger_.error("Error while communicating with backend  "
			+ e.getMessage());
	    }
	}
    }

    public boolean deleteOfflineMessage(UserID userID) {
	boolean ret = false;
	if (userID != null) {
	    this.openConnection();
	    ret = backend_.deleteOfflineMessages(userID);
	}
	return ret;
    }

}
